package cn.edu.ctbu.boostraptable.controller;
import cn.edu.ctbu.BoostrapTable.domain.Student;
import cn.edu.ctbu.BoostrapTable.helper.PageUtils;
import cn.edu.ctbu.BoostrapTable.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;


@RestController
@RequestMapping("/webapi/student")
public class StudentController {
    @Autowired
    StudentService studentService;

    /**
     * 后端验证
     */
    @PostMapping("/insert")
    public Student insert(@Valid Student student, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            // 处理验证错误，例如返回错误信息
            System.out.println("后端验证发生错误");
            return null;
        } else {
            Student student1 = studentService.insert(student);
            return student1;
        }
    }


    /**
     * 查找所有数据
     */
    @GetMapping("/findall")
    public PageUtils getAll(Integer pageSize, Integer pageNum) {
        Pageable pageable= PageRequest.of(pageNum-1,pageSize);
        Page<Student> tempStudents = studentService.getAll(pageable);
        PageUtils pageUtils=new PageUtils(tempStudents.getTotalElements(),tempStudents.getContent());
        return pageUtils;
    }

    /**
     * 根据id查找
     */
    @GetMapping("/findbyid/{id}")
    public Student findById(@PathVariable Integer id){
        return studentService.findById(id);
    }

    @GetMapping("/findbyname/{name}")
    public List<Student> findByName(@PathVariable String name){
        return studentService.findByName(name);
    }

    /**
     * 增加数据
     */
//    @PostMapping("/insert")
//    public Student insert( Student student){
//        Student student1=studentService.insert(student);
//        return student1;
//    }

    /**
     * 根据删除数据
     */
    @DeleteMapping("/delete/{id}")
    public  void delete(@PathVariable Integer id){

        studentService.delete(id);
    }

    /**
     * 修改数据
     */
    @PutMapping("/update")
    public void update(Student student){
        studentService.update(student);
    }


    @RequestMapping(value="list", method= RequestMethod.GET)
    public ModelAndView login(){
        ModelAndView mv = new ModelAndView("student/list");
        return mv;
    }
}
